from typing import Optional

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


# 这道题说人话就是：只允许左子树为空时用()替代节点，如果右子树为空或者左右子树都为空就不要瞎折腾了
# 如果 root 左右子节点都不存在，则返回 root
# 如果 root 左右子节点都存在，则返回 root(left)(right)
# 如果 root 只有左节点存在，则返回 root(left)
# 如果 root 只有右节点存在，则返回 root()(right)
class Solution:
    def tree2str_1(self, root: Optional[TreeNode]) -> str:
        # 方法一：递归
        if root is None:
            return ""
        if root.left is None and root.right is None:
            return str(root.val)
        if root.right is None:
            return f"{root.val}({self.tree2str_1(root.left)})"
        return f"{root.val}({self.tree2str_1(root.left)})({self.tree2str_1(root.right)})"

    # 方法二：迭代
    def tree2str(self, root: Optional[TreeNode]) -> str:
        ans = ""
        st = [root] # debug一下
        vis = set()
        while st:
            # 迭代法，这儿有些难理解？？？
            # 取列表的最后一个
            node = st[-1] # debug一下
            if node in vis: # 在集合里
                if node != root: # 不等于根节点
                    ans += ")"
                st.pop() # 把列表最后一个，去掉
            else: # 不在集合里
                vis.add(node) # 加入列表
                if node != root: # 不等于根节点
                    ans += "("
                ans += str(node.val) # 节点值
                if node.left is None and node.right: # 左节点空，右节点非空
                    ans += "()"
                if node.right: # 有右节点，加入
                    st.append(node.right)
                if node.left: # 有左节点，加入
                    st.append(node.left)
        return ans


def stringToTreeNode(input):
    """ 字符串转为二叉树 不太明白？？？ 回头再理解？？"""
    input = input.strip()
    input = input[1:-1]
    if not input:
        return None

    inputValues = [s.strip() for s in input.split(',')]
    root = TreeNode(int(inputValues[0]))

    nodeQueue = [root] # 队列
    front = 0
    index = 1
    while index < len(inputValues):
        node = nodeQueue[front]
        front = front + 1

        item = inputValues[index]
        index = index + 1
        if item != "null":
            leftNumber = int(item)
            node.left = TreeNode(leftNumber)
            nodeQueue.append(node.left)

        if index >= len(inputValues):
            break

        item = inputValues[index]
        index = index + 1
        if item != "null":
            rightNumber = int(item)
            node.right = TreeNode(rightNumber)
            nodeQueue.append(node.right)
    return root


def main():
    import sys
    import io
    def readlines():
        for line in io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8'):
            yield line.strip('\n')

    lines = readlines()

    while True:
        try:
            line = next(lines)
            root = stringToTreeNode(line)
            ret = Solution().tree2str(root)
            print("ret: ", ret)
        except StopIteration:
            break


if __name__ == '__main__':
    main()
    